package com.steamedfish.auctionsecurityserveroauth2.filter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.http.HttpRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

@Component
public class TokenVerifyFilter extends GenericFilterBean {

    private static final String SECRET = "shanfushanfu";

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取token
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        String jwtToken = request.getHeader("authorization");

        if (jwtToken == null) {
            jwtToken = request.getHeader("Authorization");
        }

        if (jwtToken == null) {
            jwtToken = request.getParameter("Authorization");
        }

        if (jwtToken == null) {
            jwtToken = request.getParameter("authorization");
        }



        //生成token令牌检验器
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        //使用检验器进行检验
        DecodedJWT decodedJWT = null;

        try {
            decodedJWT = verifier.verify(jwtToken);

        } catch (Exception e) {
            logger.info("没有登陆");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //获取当前用户名
        String username = decodedJWT.getClaim("username").asString();

        //获取权限
        List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(decodedJWT.getClaim("authorities").asString());

        //生成UsenamePasswordAuthenticationToken
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, null, authorities);

        //将用户名生成Token写入安全上下文
        SecurityContextHolder.getContext().setAuthentication(token);

        //进入下一个过滤器
        filterChain.doFilter(servletRequest, servletResponse);

    }
}